﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UI;
using ProtoBuf.Message;
using Battle;
using Dict.DataModel;

namespace Room
{
    public class RCAIUnionFightBase : RCAIBase
    {
        protected int camp = 2;
        public GameObject hpObj;


        public void ShowWordTip(RoomCharactor rc, int num, WordType wt)
        {
            var wordTip = GameObjectPoolManager.Instance.Spawn(RoomUnionFight.WORD_TIP);
            Vector3 pos = rc.transform.position;

            pos.y += rc.lod.GetHeight() + UnityEngine.Random.Range(0.1f, 0.5f);
            pos.x += UnityEngine.Random.Range(-0.4f, 0.4f);


            pos = CameraTool.Instance.sceneCamera.WorldToScreenPoint(pos);
            pos = UICamera.currentCamera.ScreenToWorldPoint(pos);
            pos.z = 0f;
            var wordTipTrans = wordTip.transform;
            wordTipTrans.SetParent(RoomUIManager.Instance.transform);
            wordTipTrans.transform.localScale = Vector3.one;
            wordTipTrans.transform.localEulerAngles = Vector3.zero;
            wordTipTrans.transform.position = pos;
            if (wt == WordType.ADD)
            {
                wordTip.GetComponent<BloodWordKit>().ShowHeal(num);
            }
            else if (wt == WordType.DAMAGE)
            {
                wordTip.GetComponent<BloodWordKit>().ShowNumber(num);
            }
            else if (wt == WordType.MISS)
            {
                wordTip.GetComponent<BloodWordKit>().ShowMiss();
            }
            else if (wt == WordType.IMMUNE)
            {
                wordTip.GetComponent<BloodWordKit>().ShowImmune();
            }
            else if (wt == WordType.CRIT)
            {
                wordTip.GetComponent<BloodWordKit>().ShowCrit(num);
            }

            GameObjectPoolManager.Instance.Unspawn(wordTip, 1.3f);
        }

        public override void SetHp(float hp)
        {
            if (hpObj == null)
            {
                hpObj =  GameObjectPoolManager.Instance.Spawn(RoomUnionFight.BLOOD_BAR);

                var tr = owner.transform;
                hpObj.transform.SetParent(tr);
                hpObj.transform.localScale = Vector3.one;
                hpObj.transform.localPosition = new Vector3(0, owner.lod.GetHeight(), 0);
                hpObj.SetActive(true);
            }
            else
            {
                hpObj.SetActive(true);
            }

            var kit = hpObj.GetComponent<BloodBarNumControl>();
            kit.Init();
            kit.SetNowBarValue(hp, float.MaxValue);
            if(hp<=0f)
            {
                ShowHp(false);
            }
        }
        
        public void ShowHp(bool show)
        {
            if(hpObj!=null)
            {
                var kit = hpObj.GetComponent<BloodBarNumControl>();
                kit.Show(show ? float.MaxValue : 0);
                hpObj.SetActive(show);
            }
        }

        public override void DoStop()
        {
            if(hpObj!=null)
            {
                Unspawn(hpObj);
            }
        }

        public virtual void SetCamp(int camp)
        {
            this.camp = camp;
        }

        public int Camp
        {
            get
            {
                return this.camp;
            }
        }

        public RoomNetUnionFight GetRoomNet()
        {
            var room = RoomManager.currentRoom as RoomUnionFight;
            if(room != null)
            {
                return (RoomNetUnionFight)room.netManager;
            }

            return null;
        }

        public string url;
        public GameObject sceneObj;
        public Animation objAni;

        public Dictionary<long, TableBuff> dictBuffs;
        public Dictionary<long, InstUFBuff> instBuffs;

        public RCAIUnionFightBase(RoomCharactor owner)
            : base(owner)
        {
            dictBuffs = new Dictionary<long, TableBuff>();
            instBuffs = new Dictionary<long, InstUFBuff>();
        }


        public void FindSceneObj(string url)
        {
            this.url = url;
            if (sceneObj == null)
            {
                sceneObj = GameObject.Find(url);
            }
            if (sceneObj == null)
            {
                Debug.LogError("[ERROR] scene model is not find " + url);
            }
            else
            {
                if (objAni == null)
                {
                    var ani = sceneObj.GetComponentInChildren<Animation>();
                    if (ani != null)
                    {
                        objAni = ani;
                    }
                }
            } 
        }
        
        public void PlaySceneAni(string aniName, WrapMode wrap= WrapMode.Once,bool isCross=true)
        {
            if (objAni != null)
            {
                objAni.wrapMode = wrap;
                if(isCross)
                {
                    if (objAni.GetClip(aniName) != null)
                        objAni.CrossFade(aniName);
                }
                else
                {
                    if (objAni.IsPlaying(aniName))
                    {
                        objAni.Stop();
                    }
                    objAni.Play(aniName);
                }
            }
            else
            {
                Debug.LogWarning("SceneAnimation is NULL [" + aniName+"]"+" scene url:["+url+"]");
            }
        }

        /// <summary>
        /// 被攻击
        /// </summary>
        protected virtual void BeHit(RoomCharactor srcOwner)
        {

        }

        /// <summary>
        /// 被摧毁
        /// </summary>
        protected virtual void BeDestroy(RoomCharactor srcOwner)
        {
            if(this.sceneObj!=null)
            {
                sceneObj.SetActive(false);
            }
        }

        #region buff

        GameObject buffObj;
        public virtual void LoadBuff(InstUFBuff buff)
        {
            instBuffs[buff.guid] = buff;
            dictBuffs[buff.guid] = Dict.Blo.DictBuffBlo.GetTableBuff(buff.buffId);

            var loadEffect = dictBuffs[buff.guid].EffectOn;
            if(!string.IsNullOrEmpty(loadEffect))
            {
                Spawn(loadEffect, 1f);
            }

            var lastEffect = dictBuffs[buff.guid].LastEffect;
            if(!string.IsNullOrEmpty(lastEffect))
            {
                buffObj = Spawn(lastEffect);
            }
        }

        public virtual void TickHp(RoomCharactor src, float hpDelta) { }
        
        public virtual void UnloadBuff(InstUFBuff buff)
        {
            var unloadEffect = Dict.Blo.DictBuffBlo.GetTableBuff(buff.buffId).EffectOff;
            if(!string.IsNullOrEmpty(unloadEffect))
            {
                Spawn(unloadEffect, 1f);
            }

            if(buffObj!=null)
            {
                Unspawn(buffObj);
            }

            if (instBuffs.ContainsKey(buff.guid))
            {
                instBuffs.Remove(buff.guid);
            }
            if(dictBuffs.ContainsKey(buff.guid))
            {
                dictBuffs.Remove(buff.guid);
            }
        }
        #endregion
        #region 加载Effect

        public GameObject Spawn(string effectName)
        {
            var str = CommonMethod.GetAssetNameFromAssetBundleName(effectName);
            var obj = GameObjectPoolManager.Instance.Spawn(effectName, str);
            obj.transform.SetParent(owner.transform);
            obj.transform.localScale = Vector3.one;
            obj.transform.localPosition = Vector3.zero;
            obj.SetActive(true);
            return obj;
        }

        public GameObject Spawn(string effectName,float delay)
        {
            var obj = Spawn(effectName);
            RoomManager.currentRoom.StartCoroutine(_Unspawn(obj,delay));
            return obj;
        }

        public GameObject SpawnOnUI(string effectName,float delay = 0)
        {
            var str = CommonMethod.GetAssetNameFromAssetBundleName(effectName);
            var obj = GameObjectPoolManager.Instance.Spawn(effectName, str);
            obj.transform.SetParent(PageManager.Instance.transform);
            obj.transform.localScale = Vector3.one;
            obj.transform.localPosition = Vector3.zero;
            obj.SetActive(true);
            if (delay > 0)
                RoomManager.currentRoom.StartCoroutine(_Unspawn(obj, delay));
            return obj;
        }

        private IEnumerator _Unspawn(GameObject obj,float delay)
        {
            yield return new WaitForSeconds(delay);
            Unspawn(obj);
        }

        public void Unspawn(GameObject obj)
        {
            if (obj != null)
            {
                GameObjectPoolManager.Instance.Unspawn(obj);
            }
        }
        #endregion
        
    }
}